/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-14
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-12
 * @Description:  类似Element plus风格的Message
 */

// 使用示例：
// 初始化（在main函数）
// Message.initialize(globalNavigatorKey);

// 显示成功消息
// Message.success('这是一条成功消息');

// 显示错误消息（自定义显示时间）
// Message.error('操作失败，请重试', duration: Duration(seconds: 5));

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;

// 定义消息类型
enum MessageType { success, info, warning, error, mobile }

// 定义全局导航键（在main.dart中初始化）
GlobalKey<NavigatorState> _messageNavigatorKey = GlobalKey();

class Message {
  // 初始化方法
  static void initialize(GlobalKey<NavigatorState> navigatorKey) {
    _messageNavigatorKey = navigatorKey;
  }

  // 成功消息
  static void success(String message, {Duration? duration}) {
    _showMessage(message, MessageType.success, duration);
  }

  // 信息消息
  static void info(String message, {Duration? duration}) {
    _showMessage(message, MessageType.info, duration);
  }

  // 警告消息
  static void warning(String message, {Duration? duration}) {
    _showMessage(message, MessageType.warning, duration);
  }

  // 错误消息
  static void error(String message, {Duration? duration}) {
    _showMessage(message, MessageType.error, duration);
  }

  // mobile消息
  static void mobile(String message, {Duration? duration}) {
    _showMessage(message, MessageType.mobile, duration);
  }

  static void _showMessage(
      String message, MessageType type, Duration? duration) {
    MessageManager().addMessage(
      MessageItem(
        message: message,
        type: type,
        duration: duration ?? const Duration(seconds: 3),
      ),
    );
  }
}

class MessageItem {
  final String message;
  final MessageType type;
  final Duration duration;
  final String id = DateTime.now().millisecondsSinceEpoch.toString();

  MessageItem({
    required this.message,
    required this.type,
    required this.duration,
  });
}

class MessageManager {
  static final MessageManager _instance = MessageManager._internal();
  factory MessageManager() => _instance;
  MessageManager._internal();

  final List<MessageItem> _messages = [];
  OverlayEntry? _overlayEntry;

  void addMessage(MessageItem item) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _messages.insert(0, item);
      _createOrUpdateOverlay();
      _scheduleAutoDismiss(item);
    });
  }

  void _createOrUpdateOverlay() {
    final overlayState = _messageNavigatorKey.currentState?.overlay;
    if (overlayState == null) return;

    if (_overlayEntry == null) {
      _overlayEntry = OverlayEntry(
        builder: (_) => _MessageContainer(messages: _messages),
      );
      overlayState.insert(_overlayEntry!);
    } else {
      _overlayEntry!.markNeedsBuild();
    }
  }

  void removeMessage(MessageItem item) {
    _messages.remove(item);
    if (_messages.isEmpty) {
      _overlayEntry?.remove();
      _overlayEntry = null;
    } else {
      _overlayEntry?.markNeedsBuild();
    }
  }

  void _scheduleAutoDismiss(MessageItem item) {
    Future.delayed(item.duration, () => removeMessage(item));
  }
}

// 用于显示消息列表的容器，展示所有消息
class _MessageContainer extends StatelessWidget {
  final List<MessageItem> messages; // 消息列表

  const _MessageContainer({required this.messages});

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: MediaQuery.of(context).padding.top + 20, // 设置消息距离顶部的高度
      left: 0,
      right: 0,
      child: Material(
        color: Colors.transparent, // 背景透明
        child: Column(
          children: messages
              .map((item) => _MessageWidget(item: item))
              .toList(), // 显示每条消息
        ),
      ),
    );
  }
}

// 每条消息的显示组件
class _MessageWidget extends StatefulWidget {
  final MessageItem item; // 消息项

  const _MessageWidget({required this.item});

  @override
  __MessageWidgetState createState() => __MessageWidgetState();
}

// _MessageWidget 的状态管理
class __MessageWidgetState extends State<_MessageWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller; // 动画控制器
  late Animation<double> _opacityAnimation; // 透明度动画

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 300), // 动画时长 300ms
      vsync: this,
    );
    _opacityAnimation = Tween<double>(begin: 0, end: 1).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOut), // 透明度动画曲线
    );
    _controller.forward(); // 启动动画
  }

  @override
  Widget build(BuildContext context) {
    final isMobileType = widget.item.type == MessageType.mobile;
    return FadeTransition(
      opacity: _opacityAnimation, // 应用透明度动画
      child: Container(
        margin:
            const EdgeInsets.symmetric(vertical: 8, horizontal: 20), // 设置外边距
        decoration: BoxDecoration(
          color: _getBackgroundColor(), // 根据消息类型设置背景色
          borderRadius: BorderRadius.circular(8), // 设置圆角
          boxShadow: [
            BoxShadow(
              color: Colors.black26,
              blurRadius: 6,
              offset: Offset(0, 3), // 设置阴影
            )
          ],
        ),
        padding:
            const EdgeInsets.symmetric(horizontal: 16, vertical: 12), // 内边距
        child: Row(
          mainAxisSize: MainAxisSize.min, // 根据内容调整宽度
          mainAxisAlignment: MainAxisAlignment.center, // 内容居中
          children: [
            if (!isMobileType)
              Icon(_getIcon(), color: Colors.white, size: 20), // 显示图标
            const SizedBox(width: 8),
            Flexible(
              child: Text(widget.item.message,
                  style: TextStyle(
                    color: isMobileType
                        ? Color.fromARGB(255, 52, 52, 52)
                        : Colors.white,
                    fontSize: 14,
                  )), // 显示消息内容
            ),
            const SizedBox(width: 16),
            isMobileType
                ? Container(
                    width: 22,
                    height: 22,
                    decoration: BoxDecoration(
                      color: Colors.green,
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.check,
                      color: Colors.white,
                      size: 16,
                    ),
                  )
                : GestureDetector(
                    onTap: _dismiss, // 点击关闭按钮时消失
                    child: Icon(Icons.close,
                        color: Colors.white, size: 16), // 关闭按钮
                  )
          ],
        ),
      ),
    );
  }

  // 根据消息类型返回背景颜色
  Color _getBackgroundColor() {
    switch (widget.item.type) {
      case MessageType.success:
        if (kIsWeb) {}
        return const Color(0xFF67C23A); // 成功
      case MessageType.info:
        return const Color(0xFF909399); // 信息
      case MessageType.warning:
        return const Color(0xFFE6A23C); // 警告
      case MessageType.error:
        return const Color(0xFFF56C6C); // 错误
      case MessageType.mobile:
        return const Color(0xFFEBEDF0); // mobile
    }
  }

  // 根据消息类型返回对应的图标
  IconData? _getIcon() {
    switch (widget.item.type) {
      case MessageType.success:
        return Icons.check_circle; // 成功
      case MessageType.info:
        return Icons.info; // 信息
      case MessageType.warning:
        return Icons.warning; // 警告
      case MessageType.error:
        return Icons.error; // 错误
      case MessageType.mobile:
        return null; // mobile
    }
  }

  // 关闭消息的方法
  void _dismiss() {
    _controller.reverse().then((_) {
      MessageManager().removeMessage(widget.item); // 动画结束后移除消息
    });
  }

  @override
  void dispose() {
    _controller.dispose(); // 销毁控制器
    super.dispose();
  }
}
